
const echarts = window.echarts

const baseSize = document.body.offsetWidth / 1920 * 100;

const Icon = {
    Rect : 'path://M-503.5,518.7v-12h14v12H-503.5z',
    RoundRect : 'path://M-502.2,518.5v-5.8c0.5-4.1,2.8-6.2,7-6.2s6.5,2.1,7,6.2v5.8H-502.2z',
    Line : 'path://M14.55,5.09v2H.55v-2Z'
}
// 写个十六进制转化rgba 来搞点颜色变化
const hexToRgba = (hex, alpha = 1) => {
    let r = 0, g = 0, b = 0;
    if (hex.length == 4) {
        r = "0x" + hex[1] + hex[1];
        g = "0x" + hex[2] + hex[2];
        b = "0x" + hex[3] + hex[3];
    } else if (hex.length == 7) {
        r = "0x" + hex[1] + hex[2];
        g = "0x" + hex[3] + hex[4];
        b = "0x" + hex[5] + hex[6];
    }
    return "rgba(" + +r + "," + +g + "," + +b + "," + alpha + ")";
};

// 格式化 xData , 入参：柱图全量数组
/***
 *
 * @param data
 * 返回值形式： return {
 * xData:[ '重庆' , '四川' ,'北京' ,'江苏' ]
 * dataMap:{
 *     新增:[1,2,3,4,5]，
 *     在线:[1,2,3,4,5]，
 *     在线率:[1,2,3,4,5]，
 * }
 * }
 */

const formatData = (data) => {
    const xData = [], dataMap = {};
    data.forEach(item => {
        const {Name, Data} = item;
        xData.push(Name);
        for (let k in Data) {
            if (!k.includes("百分")) {
                if (!dataMap[k]) {
                    dataMap[k] = [];
                }
                dataMap[k].push(Data[k]);
            }
        }
    });
    return {xData, dataMap}
}

// 生成柱状图 series
const getSeries = (dataMap, {barSize, line = [], color , stack}) => {

    const xData = dataMap.xData,
        dataObj = dataMap.dataMap,
        legendData = [];
    const series = [];

    const defaultColor = [
        "#0B77E1",
        "#1E9F4D",
        "#07FCFE",
        "#CBE07F"
    ]

    const colors = color ? color : defaultColor;

    let index = 0, barIndex = 0;
    const barLength = Object.keys(dataObj).length - line.length;
    for (let k in dataObj) {
        const color = colors[index % colors.length];
        const isLine = line.includes(k);
        if (!isLine) {
            legendData.push({
                name: k,
                icon: Icon.RoundRect
            });
            // 柱状图
            series.push({
                name: k,
                type: "bar",
                barWidth: barSize ? barSize : baseSize * 0.15,
                barMinHeight: barIndex === (barLength - 1) ? baseSize * 0.2 : baseSize * 0.1,
                stack: stack ? stack : null,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1,
                        [
                            { offset: 0, color: hexToRgba(colors[index]) },
                            { offset: 1, color:  hexToRgba(colors[index] , 0.3)  }
                        ]
                    ),
                    barBorderRadius: barIndex === (barLength - 1) ? [baseSize * 0.08, baseSize * 0.08, 0, 0] : null
                },
                data: dataObj[k],
                cursor: "default",
                showBackground: false,
                backgroundStyle: {color: "#3050AA"},
                xAxisIndex: 0,
                yAxisIndex: 0,
                z: 1
            });
            barIndex++;
        } else {
            legendData.push({
                name: k,
                icon: Icon.Line
            });
            // 折线图
            series.push({
                name: k,
                type: "line",
                data: dataObj[k],
                lineStyle: {color},
                symbol: "circle",
                symbolSize: .08 * baseSize,
                showSymbol: true,
                smooth: true,
                itemStyle: {
                    color: "#fff",
                    borderColor: color,
                    borderWidth: 2,
                    shadowColor: color,
                    shadowBlur: .08 * baseSize
                },
                xAxisIndex: 0,
                yAxisIndex: line.length ? 1 : 0
            });
        }

        index++;
    }
    return {series, legendData}
}

// 生成统一的 tooltip
const getTooltip = (unit) => {
    const tooltip = {
        trigger: "axis",
        axisPointer: {
            snap: true,
            type: "line",
            lineStyle: {
                color: "#177B84", // 线的颜色
                width: 1, // 线宽
                type: "solid" // 线型
            }
        },
        formatter: function (res) {
            let content = res[0].axisValue + "<br>";
            res.forEach(function (item) {
                const {value, seriesType, borderColor, color, seriesName} = item;

                if (value !== "") {
                    const colors = seriesType !== "line" ? color : borderColor;
                    const values = seriesType !== "line" ? value + (unit ? unit : '') : value + '%';

                    const icon = "<span class=\"tool-icon\" style=\"" +
                        "background-color: " + colors +
                        ";display:inline-block " +
                        ";width: .1rem" +
                        ";height:.1rem " +
                        ";border-radius: 50%" +
                        ";margin-right: .1rem" +
                        "\"></span>";
                    content += icon + seriesName + "：" + values + "<br>";
                }
            });
            return content;
        },
        backgroundColor: hexToRgba("#16767F", 0.6),
        borderWidth: 0,
        textStyle: {color: "#fff", fontSize: .12 * baseSize}
    }
    return tooltip
}

// 生成统一的制图区域
const getGrid = () => {
    const grid = {
        left: .1 * baseSize,
        bottom: .1 * baseSize,
        containLabel: true,
        right: .1 * baseSize,
        top: .5 * baseSize
    }
    return grid
}

// x 轴定制
const getxAxis = (dataMap) => {
    const axisLabel = {fontSize: .1 * baseSize, color: "#fff"};
    return {
        type: "category",
        data: dataMap.xData,
        axisTick: {
            show: false //隐藏X轴刻度
        },
        axisLabel,
        axisLine: {
            lineStyle: {
                color: "#177B84"
            }
        },
        splitLine: {
            show: false,
            interval: "auto",
            lineStyle: {
                color: "#177B84",
                opacity: 1,
                width: 1,
                type: "solid" // 网格线类型，这里使用实线
            }
        }
    }
}

// y 轴定制
const getyAxis = (unit) => {
    const axisLabel = {fontSize: .1 * baseSize, color: "#fff"};
    return [
        {
            type: "value",
            name: "单位：" + unit,
            nameTextStyle: {
                fontSize: .1 * baseSize,
                color: "#fff",
                align: "center"
            },
            axisLabel,
            axisLine: {
                show: true,
                lineStyle: {
                    color: "#177B84"
                }
            },
            axisTick: {
                show: false
            },
            splitLine: {
                show: false,
                lineStyle: {
                    color: "#177B84"
                }
            }
        },
        {
            type: "value",
            name: "",
            max: (range) => range.max < 5 ? 5 : undefined,
            axisTick: {show: false},
            axisLine: {
                show: true,
                lineStyle: {
                    color: "#177B84"
                }
            },
            splitLine: {show: false},
            axisLabel: {fontSize: .1 * baseSize, color: "#fff"},
            splitNumber: 5,
            nameTextStyle: {
                color: "#FFFFFF",
                fontSize: .1 * baseSize
            }
        }]
}

// Legend 定制
const getLegend = (data) => {
    return {
        show: true,
        type: "plain",
        right: 0,
        top: .1 * baseSize,
        textStyle: {fontSize: .11 * baseSize, color: "#fff", padding: [4, 10, 2, 0]},
        itemGap: 5,
        itemWidth: .10 * baseSize,
        itemHeight: .10 * baseSize,
        data: data
    }
}


// 生成 SymbolBar Series
const getSymbolBarSeries = (data)=>{
    const { dataMap } = data
    const series = []
    const symbolUrl = '';
    const baseNum = .10 * baseSize
    for(let k in dataMap){
        series.push({
            type: 'pictorialBar',
            name: k,
            barMinHeight:baseNum * 3,
            symbol: 'image://' + symbolUrl,
            symbolRepeat: true,
            symbolSize: [ baseNum * 2.5, baseNum * 0.5],
            symbolMargin: '-15%',
            z: 12,
            itemStyle: {
                color: "#00d6fd"
            },
            hoverAnimation: true,
            label: {
                show: true,
                position: 'top',
               // offset:[0 ,  baseNum * -1],
                //  formatter: '{c}',
                fontSize:baseNum*1.2,
                color: '#fff'
            },
            data: dataMap[k],
        })
    }
    return series
}


const echartsOptions = {

    // 柱状图 与 折线图合并
    setBarChartOptions: ({data, barSize, line = [], color, unit='' , stack}) => {

        // 格式化数据
        const dataMap = formatData(data) //  { xData , dataMap }

        // 通过格式化数据 ， 生成bar Series
        const Series = getSeries(dataMap, {barSize, line, color} , stack)   // { series ，legendData  }

        const option = {
            tooltip: getTooltip(unit),
            grid: getGrid(),
            xAxis: getxAxis(dataMap),
            yAxis: getyAxis(unit),
            legend: getLegend(Series.legendData),
            series: Series.series
        };

        return option;
    },

    // Symbol 图形柱状图
    setSymbolBarOptions:({data})=>{

        // 格式化数据
        const dataMap = formatData(data) //  { xData , dataMap }

        // 通过格式化数据 ， 生成bar Series
        const series = getSymbolBarSeries(dataMap)   // { series ，legendData  }

        const option = {
            tooltip: getTooltip('户'),
            grid: getGrid(),
            xAxis: getxAxis(dataMap),
            yAxis: {
                splitLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                axisLine: {
                    lineStyle:{
                        color:'#3D6AE2'
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: '#fff',
                        fontSize: baseSize * .12
                    }
                },
            },
            legend:{
                show:false
            },
            series
        };
        return option
    },


}

export default echartsOptions;